# coding=utf-8

import re

from flask import jsonify, render_template, request
from flask_login import current_user, login_required

from . import blue_main
from ..models import User, EngineRoom, EmailStatus, Email
from .. import db


# 用户列表及新增
@blue_main.route('/user', methods=['GET', 'POST'])
@login_required
def userList():
    # 用户验证
    if current_user.name != 'Administrator':
        return render_template('403.html'), 403
    result = {'code': 0, 'data': [], 'page': {}, 'msg': u'查询用户列表成功'}
    if request.method == 'GET':
        # 页数，默认1
        page = request.args.get('page', 1, type=int)
        # 一页的数据，默认15
        per_page = request.args.get('per_page', 15, type=int)
        if int(per_page) >= 30:
            per_page = 30
        pagination = User.query.order_by(User.group_id).paginate(page, per_page=per_page, error_out=False)
        if not pagination.total:
            result['code'] = 0
            result['msg'] = u'暂无用户信息'
            return jsonify(result)
        for user in pagination.items:
            dic_user = {}
            dic_user['user_id'] = user.id
            dic_user['user_name'] = user.name
            dic_user['user_alias'] = user.alias
            dic_user['status'] = user.status
            result['data'].append(dic_user)
        page_list = []
        for p in pagination.iter_pages():
            page_list.append(p)
        result['page']['page_list'] = page_list
        result['page']['has_prev'] = pagination.has_prev
        result['page']['page'] = pagination.page
        result['page']['has_next'] = pagination.has_next
        result['page']['pages'] = pagination.pages
        return jsonify(result)
    elif request.method == 'POST':
        if request.is_json:
            data = request.get_json()
        else:
            data = request.values
        user_name = data.get('user_name')
        user_alias = data.get('user_alias')
        status = data.get('status')
        pwd = data.get('pwd')
        cpwd = data.get('cpwd')
        # 参数校验
        if not all([user_name, user_alias, pwd, cpwd]):
            result['code'] = 1
            result['msg'] = u'参数不完整'
            result.pop('data')
            result.pop('page')
            return jsonify(result)
        if status not in [True, False]:
            result['code'] = 1
            result['msg'] = u'参数不正确'
            result.pop('data')
            result.pop('page')
            return jsonify(result)
        if pwd != cpwd:
            result['code'] = 1
            result['msg'] = u'两次密码不一致'
            result.pop('data')
            result.pop('page')
            return jsonify(result)
        user_add = User(name=user_name, alias=user_alias, status=status, password=str(pwd))
        try:
            db.session.add(user_add)
            db.session.commit()
            result['msg'] = u'新建用户成功'
        except:
            # name唯一性没通过,关闭异常中的session会话
            db.session.close()
            result['code'] = 1
            result['msg'] = u'用户名已存在'
        result.pop('data')
        result.pop('page')
        return jsonify(result)


# 用户编辑
@blue_main.route('/user/<int:user_id>', methods=['GET', 'PUT', 'DELETE'])
@login_required
def user(user_id):
    if current_user.name != 'Administrator':
        return render_template('403.html'), 403
    # user_id 校验
    user_change = User.query.filter_by(id=user_id).first()
    if not user_change:
        error = {
            'code': 1,
            'msg': u'没有此用户'
        }
        return jsonify(error)
    if request.method == 'GET':
        # 返回此用户的信息
        result = {'code': 0, 'data': {}, 'msg': u'查询用户详情成功'}
        result['data']['user_id'] = user_id
        result['data']['user_name'] = user_change.name
        result['data']['user_alias'] = user_change.alias
        result['data']['status'] = user_change.status
        return jsonify(result)
    elif request.method == 'PUT':
        # 修改信息（两个表单）
        result = {'code': 0, 'msg': u'修改用户信息成功'}
        if request.is_json:
            data = request.get_json()
        else:
            data = request.values
        form_type = data.get('form_type')
        user_alias = data.get('user_alias')
        status = data.get('status')
        pwd = data.get('pwd')
        cpwd = data.get('cpwd')
        if form_type and form_type == 'base_info':
            if not user_alias:
                result['code'] = 1
                result['msg'] = u'参数不完整'
                return jsonify(result)
            if status not in [True, False]:
                result['code'] = 1
                result['msg'] = u'参数不正确'
                return jsonify(result)
            user_change.alias = user_alias
            user_change.status = status
            db.session.commit()
            return jsonify(result)
        elif form_type and form_type == 'change_pwd':
            if not all([pwd, cpwd]):
                result['code'] = 1
                result['msg'] = u'参数不完整'
                return jsonify(result)
            if pwd != cpwd:
                result['code'] = 1
                result['msg'] = u'两次密码不一致'
                return jsonify(result)
            user_change.password = pwd
            db.session.commit()
            result['msg'] = u'密码修改成功'
            return jsonify(result)
        else:
            return render_template("404.html"), 404
    elif request.method == 'DELETE':
        result = {'code': 0, 'msg': u'已删除用户'}
        user_change.status = False
        db.session.commit()
        return jsonify(result)


# 机房列表及新增机房
@blue_main.route('/engineroom', methods=['GET', 'POST'])
@login_required
def engineroomList():
    if current_user.name != 'Administrator':
        return render_template('403.html'), 403
    result = {'code': 0, 'data': [], 'page': {}, 'msg': u'查询机房列表成功'}
    if request.method == 'GET':
        # 页数，默认1
        page = request.args.get('page', 1, type=int)
        # 一页的数据，默认15
        per_page = request.args.get('per_page', 15, type=int)
        if int(per_page) >= 30:
            per_page = 30
        pagination = EngineRoom.query.order_by(EngineRoom.name).paginate(page, per_page=per_page, error_out=False)
        if not pagination.total:
            result['code'] = 0
            result['msg'] = u'暂无机房信息'
            return jsonify(result)
        for room in pagination.items:
            dic_room = {}
            dic_room['room_id'] = room.id
            dic_room['room_name'] = room.name
            dic_room['room_alias'] = room.alias
            dic_room['status'] = room.status
            dic_room['description'] = room.script
            result['data'].append(dic_room)
        page_list = []
        for p in pagination.iter_pages():
            page_list.append(p)
        result['page']['page_list'] = page_list
        result['page']['has_prev'] = pagination.has_prev
        result['page']['page'] = pagination.page
        result['page']['has_next'] = pagination.has_next
        result['page']['pages'] = pagination.pages
        return jsonify(result)
    elif request.method == 'POST':
        if request.is_json:
            data = request.get_json()
        else:
            data = request.values
        room_name = data.get('room_name')
        room_alias = data.get('room_alias')
        status = data.get('status')
        description = data.get('description')
        if not all([room_name, room_alias]):
            result['code'] = 1
            result['msg'] = u'参数不完整'
            result.pop('data')
            result.pop('page')
            return jsonify(result)
        if status not in [True, False]:
            result['code'] = 1
            result['msg'] = u'参数不正确'
            result.pop('data')
            result.pop('page')
            return jsonify(result)
        room_add = EngineRoom(name=room_name, alias=room_alias, status=status, script=description)
        try:
            db.session.add(room_add)
            db.session.commit()
            result['msg'] = u'机房创建成功'
        except:
            # name唯一性没通过,关闭异常中的session会话
            db.session.close()
            result['code'] = 1
            result['msg'] = u'机房名已存在'
        result.pop('data')
        result.pop('page')
        return jsonify(result)


# 机房编辑
@blue_main.route('/engineroom/<int:room_id>', methods=['GET', 'PUT', 'DELETE'])
@login_required
def engineroom(room_id):
    if current_user.name != 'Administrator':
        return render_template('403.html'), 403
    result = {'code': 1, 'data': {},'msg': u'参数不完整'}
    # room_id 校验
    change_room = EngineRoom.query.filter_by(id=room_id).first()
    if not change_room:
        result['msg'] = u'没有此机房'
        result.pop('data')
        return jsonify(result)
    if request.method == 'GET':
        result['data']['room_id'] = room_id
        result['data']['room_name'] = change_room.name
        result['data']['room_alias'] = change_room.alias
        result['data']['description'] = change_room.script
        result['data']['status'] = change_room.status
        result['code'] = 0
        result['msg'] = u'查询此机房信息成功'
        return jsonify(result)
    elif request.method == 'PUT':
        if request.is_json:
            data = request.get_json()
        else:
            data = request.values
        room_alias = data.get('room_alias')
        description = data.get('description')
        status = data.get('status')
        if not room_alias:
            result.pop('data')
            return jsonify(result)
        if status not in [True, False]:
            result['msg'] = u'参数不正确'
            result.pop('data')
            return jsonify(result)
        change_room.alias = room_alias
        change_room.script = description
        change_room.status = status
        db.session.commit()
        result['code'] = 0
        result['msg'] = u'修改机房信息成功'
        result.pop('data')
        return jsonify(result)
    elif request.method == 'DELETE':
        change_room.status = False
        db.session.commit()
        result['code'] = 0
        result['msg'] = u'已删除机房'
        result.pop('data')
        return jsonify(result)


# 邮件发送历史
@blue_main.route('/emailHistory', methods=['GET'])
@login_required
def emailHistory():
    if current_user.name != 'Administrator':
        return render_template('403.html'), 403
    result = {'code': 1, 'data': [], 'page': {}, 'msg': u'暂无邮件发送记录'}
    # 页数，默认1
    page = request.args.get('page', 1, type=int)
    # 一页的数据，默认15
    per_page = request.args.get('per_page', 15, type=int)
    if int(per_page) >= 30:
        per_page = 30
    # 按时间倒叙返回
    emails = EmailStatus.query.order_by(EmailStatus.ctime.desc()).paginate(page, per_page=per_page, error_out=False)
    if not emails.total:
        result['code'] = 0
        return jsonify(result)
    for email in emails.items:
        dic_email = {}
        dic_email['time'] = email.ctime.strftime("%Y/%m/%d %H:%M:%S")
        dic_email['address'] = email.receiveaddress
        result['data'].append(dic_email)
    page_list = []
    for p in emails.iter_pages():
        page_list.append(p)
    result['page']['page_list'] = page_list
    result['page']['has_prev'] = emails.has_prev
    result['page']['page'] = emails.page
    result['page']['has_next'] = emails.has_next
    result['page']['pages'] = emails.pages
    result['code'] = 0
    result['msg'] = u'查询邮件发送记录成功'
    return jsonify(result)


# 收件地址列表及新增收件地址
@blue_main.route('/receive', methods=['GET', 'POST'])
@login_required
def receiveList():
    if current_user.name != 'Administrator':
        return render_template('403.html'), 403
    result = {'code': 1, 'data': [], 'page': {}, 'msg': u'暂无收件地址'}
    if request.method == 'GET':
        # 页数，默认1
        page = request.args.get('page', 1, type=int)
        # 一页的数据，默认15
        per_page = request.args.get('per_page', 15, type=int)
        if int(per_page) >= 30:
            per_page = 30
        emails = Email.query.order_by(Email.name).paginate(page, per_page=per_page, error_out=False)
        if not emails.total:
            result['code'] = 0
            return jsonify(result)
        for email in emails.items:
            dic_receive = {}
            dic_receive['receive_id'] = email.id
            dic_receive['receive_name'] = email.name
            dic_receive['receive_alias'] = email.alias
            dic_receive['address'] = email.address
            result['data'].append(dic_receive)
        page_list = []
        for p in emails.iter_pages():
            page_list.append(p)
        result['page']['page_list'] = page_list
        result['page']['has_prev'] = emails.has_prev
        result['page']['page'] = emails.page
        result['page']['has_next'] = emails.has_next
        result['page']['pages'] = emails.pages
        result['code'] = 0
        result['msg'] = u'查询收件地址列表成功'
        return jsonify(result)
    elif request.method == 'POST':
        if request.is_json:
            data = request.get_json()
        else:
            data = request.values
        receive_name = data.get('receive_name')
        receive_alias = data.get('receive_alias')
        address = data.get('address')
        if not all([receive_name, receive_alias, address]):
            result['msg'] = u'参数不完整'
            result.pop('data')
            result.pop('page')
            return jsonify(result)
        str_address = address.encode('utf-8')
        if not re.match('^[0-9a-zA-Z_.-]+@[0-9a-zA-Z]+(\.[0-9a-zA-Z]+)*\.[a-zA-Z0-9]{2,6}$', str_address):
            result.pop('data')
            result.pop('page')
            result['msg'] = u'邮箱格式不正确'
            return jsonify(result)
        add_receive = Email(name=receive_name, alias=receive_alias, address=address)
        try:
            db.session.add(add_receive)
            db.session.commit()
            result['code'] = 0
            result['msg'] = u'新增收件地址成功'
        except:
            db.session.close()
            result['msg'] = u'收件名称已存在'
        result.pop('data')
        result.pop('page')
        return jsonify(result)


# 收件地址编辑
@blue_main.route('/receive/<int:receive_id>', methods=['GET', 'PUT', 'DELETE'])
@login_required
def receive(receive_id):
    if current_user.name != 'Administrator':
        return render_template('403.html'), 403
    result = {'code': 1, 'data': {}, 'msg': u'参数不完整'}
    # receive_id 校验
    change_receive = Email.query.filter_by(id=receive_id).first()
    if not change_receive:
        result['msg'] = u'没有此收件地址'
        result.pop('data')
        return jsonify(result)
    if request.method == 'GET':
        result['data']['receive_id'] = change_receive.id
        result['data']['receive_name'] = change_receive.name
        result['data']['receive_alias'] = change_receive.alias
        result['data']['status'] = change_receive.status
        result['data']['address'] = change_receive.address
        result['code'] = 0
        result['msg'] = u'查询此收件地址成功'
        return jsonify(result)
    elif request.method == 'PUT':
        if request.is_json:
            data = request.get_json()
        else:
            data = request.values
        receive_alias = data.get('receive_alias')
        address = data.get('address')
        if not all([receive_alias, address]):
            result.pop('data')
            return jsonify(result)
        str_address = address.encode('utf-8')
        if not re.match('^[0-9a-zA-Z_.-]+@[0-9a-zA-Z]+(\.[0-9a-zA-Z]+)*\.[a-zA-Z0-9]{2,6}$', str_address):
            result['msg'] = u'邮箱格式不正确'
            result.pop('data')
            return jsonify(result)
        change_receive.alias = receive_alias
        change_receive.address = address
        db.session.commit()
        result['code'] = 0
        result['msg'] = u'修改收件地址成功'
        result.pop('data')
        return jsonify(result)
    elif request.method == 'DELETE':
        db.session.delete(change_receive)
        db.session.commit()
        result['code'] = 0
        result['msg'] = u'删除邮件地址成功'
        result.pop('data')
        return jsonify(result)


# 用户管理
@blue_main.route('/userManage',methods=['GET'])
@login_required
def backendManage():
    return render_template('backend/userManage.html')


# 用户管理->修改信息
@blue_main.route('/userManage/editUser',methods=['GET'])
@login_required
def editUser():
    return render_template('backend/editUser.html')


# 机房管理
@blue_main.route('/machineManage',methods=['GET'])
@login_required
def machineRoom():
    return render_template('backend/machineManage.html')


# 邮件管理
@blue_main.route('/emailManage',methods=['GET'])
@login_required
def emailManage():
    return render_template("backend/emailManage.html")


# 邮件管理----->收件地址
@blue_main.route('/emailManage/address',methods=['GET'])
@login_required
def emailAddress():
    return render_template("backend/address.html")
